package com.github.cakin.shiro.chapter6.dao;

import com.github.cakin.shiro.chapter6.JdbcTemplateUtils;
import com.github.cakin.shiro.chapter6.entity.Permission;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import static com.github.cakin.shiro.chapter6.constant.Constant.NUM2;
import static com.github.cakin.shiro.chapter6.constant.Constant.NUM3;

/**
 * @className: PermissionDaoImpl
 * @description: 权限数据访问层实现类
 * @date: 2020/5/19
 * @author: cakin
 */
public class PermissionDaoImpl implements PermissionDao {
    /**
     * 定义jdbcTemplate
     */
    private JdbcTemplate jdbcTemplate = JdbcTemplateUtils.jdbcTemplate();

    /**
     * 功能描述：创建权限
     *
     * @param permission 权限
     * @return Permission 权限
     * @author cakin
     * @date 2020/5/19
     */
    public Permission createPermission( final Permission permission ) {
        final String sql = "insert into sys_permissions(permission, description, available) values(?,?,?)";

        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        // 第2个参数 keyHolder ，里面含有主键id的信息
        jdbcTemplate.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement( Connection connection ) throws SQLException {
                // 第2个参数含义：an array of column names indicating the columns that should be returned from the inserted row or rows
                PreparedStatement psst = connection.prepareStatement(sql, new String[]{"id"});
                psst.setString(1, permission.getPermission());
                psst.setString(NUM2, permission.getDescription());
                psst.setBoolean(NUM3, permission.getAvailable());
                return psst;
            }
        }, keyHolder);
        permission.setId(keyHolder.getKey().longValue());

        return permission;
    }

    /**
     * 功能描述：删除权限
     *
     * @param permissionId 权限id
     * @author cakin
     * @date 2020/5/19
     */
    public void deletePermission( Long permissionId ) {
        // 首先把与permission关联的相关表的数据删掉
        String sql = "delete from sys_roles_permissions where permission_id=?";
        jdbcTemplate.update(sql, permissionId);

        sql = "delete from sys_permissions where id=?";
        jdbcTemplate.update(sql, permissionId);
    }

}
